package middleware

import (
	"fmt"
	"mime"
	"net/http"
	"path/filepath"
	"strconv"

	"gddgame.cc/galaxy/utils/def"
	"gddgame.cc/galaxy/utils/uuid"
)

var (
	DOWNLOAD_ERR = def.GenerateExceptionDetail(500, "DOWNLOAD_RESULT_ERROR", false)
)

func Download(context Context, next Next) error {
	err := next(nil)
	if err != nil {
		return err
	}
	i := context.GetResponse()
	var filename string
	if err := context.Get("filename", &filename); err != nil {
		filename = ""
	}
	var t string
	if err := context.Get("contentType", &t); err != nil {
		t = ""
	}
	writer := context.Writer()
	switch v := i.(type) {
	case []byte:
		if filename == "" {
			filename = uuid.RandomString()
		} else if t == "" {
			t = mime.TypeByExtension(filepath.Ext(filename))
		}
		writer.Header().Set("Content-Disposition", "attachment; filename="+filename)
		if t == "" {
			t = http.DetectContentType(v)
		}
		writer.Header().Set("Content-Type", t)
		writer.Header().Set("Content-Length", strconv.FormatInt(int64(len(v)), 10))
		_, err = writer.Write(v)
		fmt.Println("download middle", err)
		return err
	}
	context.SetResponse(DOWNLOAD_ERR)
	return nil
}
